package online.siwu.encodingviewer

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.util.Log
import android.view.Window
import android.view.WindowManager.LayoutParams
import android.widget.Toast

/**
 * Created by kilos on 2017/11/19.
 *
 */
class Extend {
}

/**
 * setWindow     window的一些设置
 * Activity 的扩展函数
 * @param fullScreen        默认为 false.   true: 全屏
 * @param actionBar        默认为 true.    true: 显示ActionBar
 * @param orientation    默认为 0: AUTO.   1: PORTRAIT    2: LANDSCAPE
 * 在setContentView()之前调用
 */
fun Activity.setWindow(fullScreen: Boolean = false, actionBar: Boolean = true, orientation: Int = 0) {
    if (fullScreen)
        window.setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN)

    if (!actionBar)
        requestWindowFeature(Window.FEATURE_NO_TITLE)

    when (orientation) {
        1 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        2 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }
}

/**
 * gotoActivity     Activity跳转
 * Activity 的扩展函数
 * @param finish       默认为 true.   true: 销毁this； false: 保留this，可以返回
 * @param activity    解释=掩饰
 * inline reified
 */
inline fun <reified activity : Activity> Activity.gotoActivity(finish: Boolean = true) {
    startActivity(Intent(this, activity::class.java))
    if (finish) finish()
}

/**
 * toast:    Toast 的简化版
 * Activity 的扩展函数
 * @param msg       Message
 * @param isLong         默认值为 false.    true: LONG； false: SHORT
 */
fun Activity.toast(msg: String, isLong: Boolean = false) {
    if (isLong)
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}

/**
 * log:    Log 的简化版
 * Activity 的扩展函数
 * @param msg       Message
 * @param tag         默认值为 "AUTO"
 */
fun Activity.log(msg: String, tag: String = "AUTO") {
    Log.i(tag, msg)
}

/**
 * toIntWithDefault 如果 String 转换出错，就用默认值代替
 * String 的扩展函数
 * @param def       默认值
 * @return Int
 */
fun String.toIntWithDefault(def: Int): Int{
    var i: Int
    try {
        i = this.toInt()
    } catch (e: NumberFormatException) {
        i = def
    }
    return i
}